package com.lamda.zhekou.task;

import com.lamda.zhekou.vo.ResultVo;
import org.jboss.netty.util.internal.ConcurrentHashMap;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created by MJiao on 15/10/8.
 */
@Service
public class TaskExecutorCenter {

    public static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TaskExecutorCenter.class);

    public static final int CommandTaskWorkerCount = 10;

    private ArrayBlockingQueue<CommandTask> arrayBlockingQueue;

    private Map<String, ResultVo> commandTaskExeResultMap;

    private volatile boolean isReady;

    public TaskExecutorCenter() {
        this.arrayBlockingQueue = new ArrayBlockingQueue<CommandTask>(10000);
        this.commandTaskExeResultMap = new ConcurrentHashMap<>();
    }

    public synchronized void prepare() {
        if (this.isReady) {
            return;
        }
        this.isReady = true;

        LOGGER.info("TaskExecutorCenter prepare...");

        for (int idx = 0; idx < CommandTaskWorkerCount; idx++) {
            CommandWorker worker = new CommandWorker(this.arrayBlockingQueue);
            worker.start();
        }
    }

    /**
     * 通知commandTask任务已经执行完成
     *
     * @param commandTask
     * @param resultVo
     */
    public void notifyCommandTaskFinish(CommandTask commandTask, ResultVo resultVo) {
        this.commandTaskExeResultMap.put(commandTask.getId(), resultVo);
    }


    /**
     * 查询任务的进行结果
     *
     * @param taskId
     * @return
     */
    public ResultVo getCommandTaskFinish(String taskId) {
        ResultVo resultVo = this.commandTaskExeResultMap.get(taskId);
        if (resultVo == null) {
            for (CommandTask commandTask : arrayBlockingQueue) {
                if (commandTask.getId().equals(taskId)) {
                    resultVo.setSucc(false);
                    resultVo.setMsg("任务正在处理中...");
                    break;
                }
            }
        }
        return resultVo;
    }

    /**
     * 提交异步任务
     *
     * @param commandTask
     */
    public void submitTask(CommandTask commandTask) {
        this.arrayBlockingQueue.add(commandTask);
    }

    /**
     * 检查是否有相同vps的任务正在执行
     *
     * @param taskId
     * @return
     */
    public boolean checkVpsHasTaskIsWaiting(String taskId) {
        for (CommandTask commandTask : arrayBlockingQueue) {
            if (commandTask.getId().equals(taskId)) {
                return true;
            }
        }
        return false;
    }
}
